from QQLoginTool.QQtool import OAuthQQ
from django.contrib.auth import login
from django.shortcuts import render,redirect
from django.views import View
from django.conf import settings
from django import http
from django_redis import get_redis_connection

from apps.oauth.models import OAuthQQUser
from apps.oauth.utils import generate_access_token, check_access_token
from apps.users.models import User
from utils.response_code import RETCODE


# Create your views here.
class QQAuthURLView(View):
    def get(self,request):
        '''
        提供qq登录扫码页面
        :param request:
        :return:
        '''
        next=request.GET.get('next')
        oauth=OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,state=next
                      )
        login_url=oauth.get_qq_url()
        return http.JsonResponse({'code':RETCODE.OK,'errmsg':'ok','login_url':login_url})

class QQAuthUserView(View):
    def get(self,request):
        '''

        :param request:
        :return:
        '''
        code=request.GET.get('code')
        if not code:
            return http.HttpResponseForbidden('获取code失败')
        try:
            oauth=OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                            redirect_uri=settings.QQ_REDIRECT_URI,)
            access_token=oauth.get_access_token(code)
            openid=oauth.get_open_id(access_token)
        except Exception as e:
            print(e)
            return http.HttpResponseForbidden('oath2.0认证失败')
        try:
            oauth_user=OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            context={
                'access_token':generate_access_token(openid)

            }
            return render(request,'oauth_callback.html',context)
        else:
            login(request,oauth_user.user)
            next=request.GET.get('state')
            response=redirect(next)
            response.set_cookie('username',oauth_user.user.username,max_age=3600*24*3)
            return response
    def post(self,request):
        '''
        处理登录回调
        :param request:
        :return:
        '''
        email=request.POST.get('email')
        password=request.POST.get('password')
        email_code_client=request.POST.get('email_code')
        access_token=request.POST.get('access_token')
        print(access_token,'access_token')
        redis_conn=get_redis_connection('verify_code')
        email_code_server=redis_conn.get('email_%s'%email)
        if email_code_server is None:
            return render(request,'oauth_callback.html',{'email_code_errmsg':'验证码已经失效'})
        if email_code_server.decode()!=email_code_client:
            return render(request,'oauth_callback.html',{'email_code_errmsg':'输入验证码有误'})
        openid=check_access_token(access_token)
        if not openid:
            return render(request, 'oauth_callback.html', {'email_code_errmsg': 'openid失效'})
        try:
            user=User.objects.get(email=email)
        except Exception as e:
            user=User.objects.create_user(username=email,password=password,email=email)
        else:
            if not user.check_password(password):
                return render(request,'oauth_callback.html',{'email_code_errmsg':'账号或者密码错误'})
            try:
                oauth_qq_user=OAuthQQUser.objects.create(user=user,openid=openid)
            except Exception as e:
                print(e)
                return render(request, 'oauth_callback.html', {'email_code_errmsg': '500错误'})
            login(request,oauth_qq_user.user)
            next=request.GET.get('state')
            if next:
                response=redirect(next)
            else:
                response=redirect('contents:index')
            response.set_cookie('username',oauth_qq_user.user.username)
            return response










